package com.test.demo.nettydemo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;

public class HelloServerHandler extends SimpleChannelInboundHandler {

    public static ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup("ChannelGroups", GlobalEventExecutor.INSTANCE);

    /**
     * 连接的时候
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("======"+ctx.channel().remoteAddress()+"======上线啦");
        ByteBuf buf = Unpooled.copiedBuffer("[客户端]======="+ctx.channel().remoteAddress()+"======上线啦", CharsetUtil.UTF_8);
        CHANNEL_GROUP.writeAndFlush(buf);
        CHANNEL_GROUP.add(ctx.channel());
    }


    /**
     * 发送消息
     * @param channelHandlerContext
     * @param o
     * @throws Exception
     */
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        ByteBuf buffer= Unpooled.copiedBuffer((byte[]) o);
        Channel mychannel = channelHandlerContext.channel();
        CHANNEL_GROUP.forEach(cn ->{
            String s=mychannel==cn?"自己":"客户端";
            ByteBuf buf = Unpooled.copiedBuffer("["+s+"]======="+cn.remoteAddress()+"======发送消息"+buffer.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8);
            cn.writeAndFlush(buf);
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("======"+ctx.channel().remoteAddress()+"======下线啦");
        ByteBuf buf = Unpooled.copiedBuffer("[客户端]======="+ctx.channel().remoteAddress()+"======下线啦", CharsetUtil.UTF_8);
        CHANNEL_GROUP.remove(ctx.channel());
        CHANNEL_GROUP.writeAndFlush(buf);
    }
}
